package io.renren.modules.mqtt;

import io.renren.modules.mqtt.service.MqttService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * //Add the class description
 *
 * @author lhb
 * @date 2023/6/6
 */
@Component
@Slf4j
public class SampleCallback implements MqttCallbackExtended {


    @Autowired
    private MqttService mqttService;

    // 连接丢失
    public void connectionLost(Throwable cause) {
        log.debug("===>>>mqtt连接断开：" + cause.getMessage());
//        mqttConfiguration.getPushClient();
//        try {
//            client.refresh();
//        } catch (Exception e) {
//            log.debug("重新链接失败:" + e.getMessage());
//        }
    }

    //  收到消息
    public void messageArrived(String topic, MqttMessage message) {
        mqttService.handleMqttMessage(topic, message);
    }

    // 消息传递成功
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.debug("消息发送成功");
    }

    @Override
    public void connectComplete(boolean b, String s) {
        log.debug("----连接成功：" + s);
        try {
            mqttService.subscribe(MqttPushClient.mqttClient);
        } catch (MqttException e) {
            log.debug("订阅主体失败:" + e.getMessage());
        }
    }
}
